var express = require('express');
var router = express.Router();
const commonDao = require('../dao/commonDao');
const async = require('async');

let gameServerInterfaceServices = require('../services/gameServerInterfaceServices');

/* GET home page. */
router.post('/addNew', function (req, res, next) {


  if (!req.session.uid) {
    res.send({ code: code.INVALID_UERS });
    return;
  }

  let robotData = req.body;
  let userId = robotData.userId;
  if (userId) {
    //更新机器人基础信息
    robotData.address = JSON.stringify({ 'x': robotData.latitude, 'y': robotData.longitude });
    // let addUnionInfo = {
    //   spreaderID: unionData.ownerUid,
    //   unionID: robotData.unionID,
    //   joinTime: Date.now()
    // };
    commonDao.findOneAndUpdate('userModel', { '_id': userId }, robotData, (err, result) => {
      res.send({ code: 0, data: { err, result } });
    });

  } else {
    //新增机器人
    let uid = robotData.uid;
    async.waterfall([
      (cb) => {
        commonDao.findOneData('userModel', { uid }, (err, result) => {
          if (!err && result) {
            cb('UID已存在');
          } else {

            if (parseInt(robotData.unionID) > 0) {
              //查询联盟是否存在
              commonDao.findOneData('unionModel', { unionID: robotData.unionID }, (err, result) => {
                if (!err && result) {
                  cb(null, result);
                } else {
                  cb('联盟不存在');
                }
              });
            } else {
              cb(null, null);
            }


          }
        });
      },
      (unionData, cb) => {


        robotData.isRobot = true;
        robotData.createTime = Date.now();
        if (unionData) {
          let addUnionInfo = {
            spreaderID: unionData.ownerUid,
            unionID: robotData.unionID,
            joinTime: Date.now()
          };
          robotData.unionInfo = [addUnionInfo];
        }

        robotData.isBind = true; //使用绑定判断是否启用
        robotData.address = JSON.stringify({ 'x': robotData.latitude, 'y': robotData.longitude });
        commonDao.createData('userModel', robotData, (err, result) => {
          if (!err && result) {
            cb(null);
          } else {
            cb('新增失败');
          }
        });
      }
    ], function (err, result) {
      res.send({ code: 0, data: { err, result } });
    })

  }




});

//获取机器人列表
router.get('/list', function (req, res, next) {

  if (!req.session.uid) {
    res.send({ code: code.INVALID_UERS });
    return;
  }
  let unionID = req.query.unionID;
  let gameType = req.query.gameType;
  let searchInUse = req.query.searchInUse;
  let params = req.query;
  let startIndex = parseInt(params.offset);
  let count = parseInt(params.limit);
  let query = { isRobot: true, isReback: { $ne: true } };
  if (unionID) {
    query.unionID = parseInt(unionID);
  }
  if (gameType != '-1') {
    query.gameType = parseInt(gameType);
  }
  // if (searchInUse == '1') {
  //   query.unionID = { $neq: 0 };
  // } else if (searchInUse == '2') {
  //   query.unionID = { $eq: 0 };
  // }


  commonDao.findDataAndCount('userModel', startIndex, count, { "_id": -1, isBind: 1 }, query, function (err, data, count) {
    res.send({ rows: data, total: count });
  });

});


//启用 停用机器人
router.post('/band', function (req, res, next) {

  let robotData = req.body;
  commonDao.findOneAndUpdate('userModel', { uid: robotData.uid }, { isBind: JSON.parse(robotData.isBind) }, function (err) {
    res.send({ code: 0 });
  });

});

//机器人回收
router.post('/reback', function (req, res, next) {

  let robotData = req.body;
  // 查询用户数据
  commonDao.findOneData('userModel', { uid: robotData.uid, 'isRobot': true }, function (err, userData) {

    if (!err && userData) {

      if (userData.roomID != "" && userData.roomID != 0) {
        //在游戏中时等待游戏结束时回收
        commonDao.findOneAndUpdate('userModel', robotData, { isReback: true }, function (err, result) {
          res.send({ code: 0 });
        });

      } else {

        //不在游戏中
        for (let i = 0; i < userData.unionInfo.length; ++i) {
          //将分数还给盟主
          let unionInfoItem = userData.unionInfo[i];
          let totalCount = parseFloat((unionInfoItem.score + unionInfoItem.safeScore).toFixed(2));
          let unionID = unionInfoItem.unionID;
          //查找联盟的盟主
          commonDao.findOneData('unionModel', { unionID: unionID }, function (err, unionData) {
            if (!err && unionData) {
              commonDao.findOneAndUpdate('userModel', { uid: unionData.ownerUid, "unionInfo.unionID": unionInfoItem.unionID }, { $inc: { "unionInfo.$.score": totalCount } }, function (err, result) {
                if (!err && result && result.unionInfo) {
                  gameServerInterfaceServices.updateUserDataNotify(unionData.ownerUid, ['unionInfo']);
                }
              });
            }
          });
        }
        // 删除联盟数据
        commonDao.findOneAndUpdate('userModel', robotData, { unionInfo: [], unionID: 0, isBind: false }, function (err, result) {
          res.send({ code: 0 });
        });
      }


    } else {
      //数据不对
      res.send({ code: -1 });
    }

  });


});

router.post('/readd', function (req, res, next) {


  if (!req.session.uid) {
    res.send({ code: code.INVALID_UERS });
    return;
  }

  let robotData = req.body;
  let uids = robotData.uid;
  uids = uids.split(',');

  async.waterfall([
    (cb) => {
      commonDao.findOneData('unionModel', { unionID: robotData.unionID }, (err, result) => {
        if (!err && result) {
          cb(null, result);
        } else {
          cb('联盟不存在');
        }
      });
    },
    (unionData, cb) => {


      let addUnionInfo = {
        spreaderID: unionData.ownerUid,
        unionID: robotData.unionID,
        joinTime: Date.now()
      };
      let updateInfo = {};
      updateInfo.unionInfo = [addUnionInfo];
      updateInfo.unionID = robotData.unionID;
      updateInfo.isBind = true; //使用绑定判断是否启用
      commonDao.updateAllData('userModel', { uid: { $in: uids } }, updateInfo, (err, result) => {
        if (!err && result) {
          res.send({ code: 0, data: { err, result } });
        } else {
          res.send({ code: 0, data: { err, result } });
        }
      });
    }
  ], function (err, result) {
    res.send({ code: 0, data: { err, result } });
  })



});


router.post('/retype', function (req, res, next) {


  if (!req.session.uid) {
    res.send({ code: code.INVALID_UERS });
    return;
  }

  let uid = (req.body.uid).split(',');
  let updateInfo = req.body.updateInfo;
  updateInfo = JSON.parse(updateInfo);
  commonDao.updateAllData('userModel', { uid: { $in: uid } }, updateInfo, (err, result) => {
    if (!err && result) {
      res.send({ code: 0, data: { err, result } });
    } else {
      res.send({ code: 0, data: { err, result } });
    }
  });

});


module.exports = router;
